package com.syqc.videos.players

import android.content.Context
import android.media.AudioManager
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.core.view.isGone
import androidx.core.view.isVisible
import com.shuyu.gsyvideoplayer.utils.GSYVideoType
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import com.shuyu.gsyvideoplayer.video.base.GSYBaseVideoPlayer
import com.shuyu.gsyvideoplayer.video.base.GSYVideoPlayer
import com.shuyu.gsyvideoplayer.video.base.GSYVideoViewBridge
import com.syqc.comlib.AppConfigs
import com.syqc.comlib.rx.LiveDataBus
import com.syqc.comlib.rx.filterFast
import com.syqc.monitor.R
import com.syqc.videos.interfaces.IRealPlayerListener
import com.syqc.videos.videomanager.IPlayerListener
import com.syqc.videos.videomanager.PlayerManager

class RealPlayer : StandardGSYVideoPlayer, IPlayerListener {
    constructor(context: Context?, fullFlag: Boolean?) : super(context, fullFlag)
    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)


    //数据类型
    private var mType: Int = 0

    //是否需要静音
    private var isNeedMute = true

    //是否选中当前通道
    private var isChoose = false

    //码流类型
    private var stream = AppConfigs.streamType

    //通道
    private var pass: String = ""

    private lateinit var tvSwitchScale: TextView
    private lateinit var tvSwitchStream: TextView
    private lateinit var ivSwitchVoice: ImageView
    private lateinit var rlVideo: RelativeLayout
    private lateinit var loadingProgress: ProgressBar


    override fun getLayoutId(): Int {
        return R.layout.real_video
    }

    override fun init(context: Context?) {
        super.init(context)
        initParams()
        initView()
        listener()
    }


    private fun initParams() {
        isRotateViewAuto = true
        isLockLand = true
        isReleaseWhenLossAudio = false
        isShowFullAnimation = true
        setIsTouchWiget(false)
        setIsTouchWigetFull(false)
    }

    private fun initView() {
        tvSwitchScale = findViewById(R.id.tvSwitchScale)
        tvSwitchStream = findViewById(R.id.tvSwitchStream)
        loadingProgress = findViewById(R.id.loadingProgress)
        ivSwitchVoice = findViewById(R.id.ivSwitchVoice)
        rlVideo = findViewById(R.id.rlVideo)

        tvSwitchScale.setText(R.string.desc_video_default_ratio)
        GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_DEFAULT)

        isNeedMute = true
        ivSwitchVoice.isSelected = isNeedMute

        stream = AppConfigs.streamType
        changeStream(stream)
    }

    private fun listener() {
        onAudioFocusChangeListener = AudioManager.OnAudioFocusChangeListener { focusChange ->
            when (focusChange) {
                AudioManager.AUDIOFOCUS_GAIN -> {}
                AudioManager.AUDIOFOCUS_LOSS -> {}
                AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> {}
                AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> {}
            }
        }

        tvSwitchScale.setOnClickListener {
            if (!mHadPlay) {
                return@setOnClickListener
            }
            when (mType) {
                0 -> mType = 1
                1 -> mType = 2
                2 -> mType = 3
                3 -> mType = 4
                4 -> mType = 0
            }
            resolveTypeUI()
        }

        tvSwitchStream.filterFast {
            if (!mHadPlay) {
                return@filterFast
            }
            realListener?.onStreamChange()
            stream = if (stream == "0") "1" else "0"
            changeStream(stream)
        }

        ivSwitchVoice.setOnClickListener {
            isNeedMute = !isNeedMute
            val key = getKey()
            PlayerManager.getCustomManager(key).setNeedMute(key, isNeedMute)
        }
    }

    override fun onClick(v: View) {
        super.onClick(v)
        when (v.id) {
            R.id.surface_container -> {
                changePass()
            }
        }
    }

    /**
     * 显示比例
     * 注意，GSYVideoType.setShowType是全局静态生效，除非重启APP。
     */
    private fun resolveTypeUI() {
        if (!mHadPlay) {
            return
        }
        when (mType) {
            1 -> {
                tvSwitchScale.text = "16:9"
                GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_16_9)
            }

            2 -> {
                tvSwitchScale.text = "4:3"
                GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_4_3)
            }

            3 -> {
                tvSwitchScale.setText(R.string.desc_video_full_screen)
                GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_FULL)
            }

            0 -> {
                tvSwitchScale.setText(R.string.desc_video_default_ratio)
                GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_DEFAULT)
            }
        }
        changeTextureViewShowType()
        if (mTextureView != null) mTextureView.requestLayout()
    }

    fun changVideoType(type: Int) {
        if (!mHadPlay) {
            return
        }
        mType = type
        resolveTypeUI()
    }


    override fun resolveNormalVideoShow(
        oldF: View?,
        vp: ViewGroup?,
        gsyVideoPlayer: GSYVideoPlayer?
    ) {
        super.resolveNormalVideoShow(oldF, vp, gsyVideoPlayer)
        if (gsyVideoPlayer != null) {
            val sampleVideo: RealPlayer = gsyVideoPlayer as RealPlayer

            mType = sampleVideo.mType
            isChoose = sampleVideo.isChoose
            isNeedMute = sampleVideo.isNeedMute
            stream = sampleVideo.stream
            pass = sampleVideo.pass
            ivSwitchVoice.isSelected = sampleVideo.isNeedMute
            resolveTypeUI()
            changeAudioPass(isNeedMute)
            changeStream(stream)
        }
    }

    override fun startWindowFullscreen(
        context: Context?,
        actionBar: Boolean,
        statusBar: Boolean
    ): GSYBaseVideoPlayer {
        val sampleVideo: RealPlayer = super.startWindowFullscreen(
            context, actionBar, statusBar
        ) as RealPlayer
        sampleVideo.isChoose = isChoose
        sampleVideo.mType = mType
        sampleVideo.isNeedMute = isNeedMute
        sampleVideo.stream = stream
        sampleVideo.pass = pass
        sampleVideo.realListener = realListener
        sampleVideo.ivSwitchVoice.isSelected = isNeedMute
        sampleVideo.resolveTypeUI()
        sampleVideo.changeAudioPass(isNeedMute)
        sampleVideo.changeStream(stream)
        return sampleVideo
    }

    override fun isLockLandByAutoFullSize(): Boolean {
        var isLockLand = mLockLand
        if (isAutoFullWithSize) {
            isLockLand = !isVerticalVideo
        }
        return isLockLand
    }

    override fun touchSurfaceMoveFullLogic(absDeltaX: Float, absDeltaY: Float) {
        super.touchSurfaceMoveFullLogic(absDeltaX, absDeltaY)
        //不给触摸快进，如果需要，屏蔽下方代码即可
        mChangePosition = false

        //不给触摸音量，如果需要，屏蔽下方代码即可
        mChangeVolume = false

        //不给触摸亮度，如果需要，屏蔽下方代码即可
        mBrightness = false
    }

    override fun touchDoubleUp(e: MotionEvent?) {
//        super.touchDoubleUp(e)
    }

    //////////////////////////////////////////////////////////////////////////
    override fun getGSYVideoManager(): GSYVideoViewBridge {
        val manager = PlayerManager.getCustomManager(getKey())
        manager.initContext(context.applicationContext)
        manager.setVoiceListener(this)
        return manager
    }

    fun getKey() = "RealPlayer.$mPlayTag.$mPlayPosition"

    override fun getFullId(): Int {
        return PlayerManager.FULLSCREEN_ID
    }

    override fun getSmallId(): Int {
        return PlayerManager.SMALL_ID
    }

    override fun backFromFull(context: Context?): Boolean {
        return PlayerManager.backFromWindowFull(context, getKey())
    }

    override fun releaseVideos() {
        PlayerManager.releaseAllVideos(getKey())
    }

    /////////////////////////////////////////////////////////////////////
    override fun onMuteChange(isNeedMute: Boolean) {
        this.isNeedMute = isNeedMute
        ivSwitchVoice.isSelected = isNeedMute
    }

    override fun onPassChange(isChoose: Boolean) {
        this.isChoose = isChoose
        changeAudioPass(isChoose)
    }

    //通道
    fun setPass(pass: String) {
        this.pass = pass
    }

    //失败后展示加载中
    fun showLoadProgress(isShow: Boolean) {
        loadingProgress.isVisible = isShow
        if (isShow) startButton.isGone = true
    }

    //改变视频码流展示
    private fun changeStream(stream: String) {
        if (stream == "0") {
            tvSwitchStream.setText(R.string.desc_video_main_stream)
        } else {
            tvSwitchStream.setText(R.string.desc_video_sub_stream)
        }
    }

    //改变视频码流展示
    fun changeStreamOut(stream: String) {
        this.stream = stream
        changeStream(stream)
    }

    // 切换通道
    private fun changePass() {
        val key = getKey()
        isChoose = true
        LiveDataBus.get().with("RealPass").postValue(pass)
        PlayerManager.getCustomManager(key).setPassChoose(key, isChoose)
    }

    private fun changeAudioPass(isChoose: Boolean) {
        rlVideo.setBackgroundResource(
            if (isChoose) {
                R.mipmap.bg_video_red
            } else {
                R.mipmap.bg_video
            }
        )
    }

    /////////////////////////////////////////////////////////////////////
    private var realListener: IRealPlayerListener? = null
    fun setRealListener(listener: IRealPlayerListener) {
        realListener = listener
    }
}